package cn.com.dcsgo.util.jwt;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * JwtHelper
 *
 * @author Dcsgo
 * @since 2025/4/23 21:31
 */

public class JwtHelper {

    /**
     * token 过期时间
     */
    private static final long tokenExpiration = 365L * 24 * 60 * 60 * 1000;
    /**
     * token 签名秘钥
     */
    private static final String tokenSignKey = "uuyx";

    /**
     * 根据 userId username 生成token字符串
     *
     * @param userId   用户id
     * @param username 用户名
     * @return token字符串
     */
    public static String createToken(Long userId, String username) {
        return Jwts.builder()
                .setSubject("uuyx-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("username", username)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    public static Long getUserId(String token) {
        if (StringUtils.isEmpty(token)) return null;

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        //默认转换成Integer 为尽可能安全做以下特殊处理
        Object userIdValue = claims.get("userId");
        if (userIdValue instanceof Number) {
            return ((Number) userIdValue).longValue();
        }
        return Long.parseLong(userIdValue.toString()); // 兜底处理
    }

    public static String getUsername(String token) {
        if (StringUtils.isEmpty(token)) return "";

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return claims.get("username", String.class);
    }

    //jwt token无需删除，客户端扔掉即可。

    public static void main(String[] args) {
        String token = JwtHelper.createToken(7L, "admin");
        System.out.println(token);
        System.out.println(JwtHelper.getUserId(token));
        System.out.println(JwtHelper.getUsername(token));
    }
}
